﻿function DraftPost() {
    var self = this;
    this.editor = ko.observable();
    this.body = ko.observable();
    this.id = ko.observable();
    this.fileId = ko.observable();
    this.title = ko.observable().extend({ required: "Please enter title" });
    this.time = ko.observable();
    this.type = ko.observable();
    this.published = ko.observable();
    this.author = ko.observable();
    this.tab = ko.observable('main');
    this.meta = ko.observable();

    this.categories = ko.observableArray();
    this.selectedCategories = ko.observableArray();
    this.selectedCategoriesJson = ko.computed(function () {
        var jsonArray = new Array();
        for (var idx = 0; idx < this.selectedCategories().length; idx++)
            jsonArray.push("{ \"CatID\": \"" + this.selectedCategories()[idx] + "\" }");
        return "[" + jsonArray.join() + "]";
    }, this);

    this.oldCategories = ko.observableArray();
    this.oldCategoriesJson = ko.computed(function () {
        var jsonArray = new Array();
        for (var idx = 0; idx < this.oldCategories().length; idx++)
            jsonArray.push("{ \"CatID\": \"" + this.oldCategories()[idx] + "\" }");
        return "[" + jsonArray.join() + "]";
    }, this);

    this.tags = ko.observableArray();
    this.oldTags = ko.observableArray();
    this.selectedTags = ko.observableArray();
    this.selectedTagsJson = ko.computed(function () {
        var jsonArray = new Array();
        for (var idx = 0; idx < this.selectedTags().length; idx++)
            jsonArray.push("{ \"TagId\": \"" + this.selectedTags()[idx] + "\" }");
        return "[" + jsonArray.join() + "]";
    }, this);
    this.oldTagsJson = ko.computed(function () {
        var jsonArray = new Array();
        for (var idx = 0; idx < this.oldTags().length; idx++)
            jsonArray.push("{ \"TagId\": \"" + this.oldTags()[idx] + "\" }");
        return "[" + jsonArray.join() + "]";
    }, this);

    this.attachments = ko.observableArray();
    this.attachmentsJson = ko.computed(function () {
        var jsonArray = new Array();
        for (var idx = 0; idx < this.attachments().length; idx++)
            jsonArray.push(this.attachments()[idx].toJson());
        return "[" + jsonArray.join() + "]";
    }, this);

    this.ie = ko.observable();

    this.previewContent = ko.observable();

    this.successMessage = ko.observable();
    this.errors = ko.observableArray();
    this.errorMessage = ko.computed({
        read: function () {
            var html = '';
            if (this.errors().length > 0)
                html += this.errors()[0];
            if (this.errors().length > 1) {
                html += "<ul>"
                for (var idx = 1; idx < this.errors().length; idx++)
                    html += "<li>" + this.errors()[idx] + "</li>";
                html += "</ul>";
            }
            return html;
        },
        write: function (value) {
            this.errors.removeAll();
            this.errors.push(value);
        },
        owner: this
    });

    this.composeMain = function (d, e) {
        if (!this.isMain()) {
            this.tab('main')
            this.setActiveTab(e.currentTarget);
        }
    }

    this.isMain = ko.computed(function () {
        return this.tab() == 'main';
    }, this);

    this.composeMeta = function (d, e) {
        if (!this.isMeta()) {
            this.tab('meta');
            this.setActiveTab(e.currentTarget);
        }
    }

    this.isMeta = ko.computed(function () {
        return this.tab() == 'meta';
    }, this);

    this.preview = function (d, e) {
        if (!this.isPreview()) {
            this.previewContent(this.editor().getData());
            this.tab('preview');
            this.setActiveTab(e.currentTarget);
        }
    }

    this.isPreview = ko.computed(function () {
        return this.tab() == 'preview';
    }, this);

    this.setActiveTab = function (elem) {
        $('.tabs > input[type=button]').removeClass('active-tab');
        $(elem).addClass('active-tab');
    }

    this.load = function (item) {
        this.id(item.DraftID);
        this.fileId(item.FileID);
        this.title(item.Title);
        this.type(item.Type);
        this.published(item.Type == 2);
        this.time(item.FormattedTime);
        for (var idx = 0; idx < item.Categories.length; idx++) {
            var category = item.Categories[idx];
            this.selectedCategories.push(category.CatID);
        }
        for (var idx = 0; idx < item.Tags.length; idx++) {
            var tag = item.Tags[idx];
            this.selectedTags.push(tag.TagId);
        }
    }

    this.loadJson = function (item) {
        var post = item.Post;
        this.load(post);
        this.author(post.Author);
        this.body(post.Contents);
        this.meta(post.Meta);
        for (var idx = 0; idx < post.Documents.length; idx++) {
            var document = post.Documents[idx];
            this.attachments.push(new Attachment(this.attachments, document.VirtualPath, this.id()));
        }
        for (var idx = 0; idx < post.OldCategories.length; idx++) {
            var oldCategory = post.OldCategories[idx];
            this.oldCategories.push(oldCategory.CatID);
        }
        for (var idx = 0; idx < item.Categories.length; idx++) {
            var category = item.Categories[idx];
            this.categories.push(new option(category.Id, category.Name));
        }
        for (var idx = 0; idx < item.Tags.length; idx++) {
            var tag = item.Tags[idx];
            this.tags.push(new option(tag.Id, tag.Name));
        }
        for (var idx = 0; idx < post.OldTags.length; idx++) {
            var oldTag = post.OldTags[idx];
            this.oldTags.push(oldTag.TagId);
        }
        setInterval(function () {
            self.autoSave();
        }, 60000);
    }

    this.editLink = ko.computed(function () {
        return appPath + 'Post/Compose/' + this.id();
    }, this);

    this.hasError = ko.computed(function () {
        return this.title.hasError();
    }, this);

    this.setError = function () {
        if (this.hasError()) {
            self.errorMessage("Please correct the following errors:");
            if (this.title.hasError())
                self.errors.push(this.title.validationMessage());
        } else {
            self.clearError();
        }
    }

    this.clearError = function () {
        self.errors.removeAll();
    }

    this.autoSave = function () {
        if (!this.hasError())
            this.save();
    }

    this.save = function () {
        if (this.hasError()) {
            this.setError();
        } else {
            var url = appPath + 'Post/Save/'
            var input = {
                DraftID: this.id(),
                FileID: this.fileId(),
                Type: this.type(),
                Title: this.title(),
                Meta: this.meta(),
                Contents: this.editor().getData(),
                Time: this.time(),
                Categories: this.selectedCategoriesJson(),
                OldCategories: this.oldCategoriesJson(),
                Tags: this.selectedTagsJson(),
                OldTags: this.oldTagsJson(),
                Documents: this.attachmentsJson()
            };

            $.post(url, input, function (data) {
                if (data.Result) {
                    self.successMessage(data.Message);
                    if (data.Data != '')
                        self.id(data.Data);
                    self.clearError();
                } else {
                    self.errorMessage(data.Message);
                    if (data.Errors) {
                        for (var idx = 0; idx < data.Errors.length; idx++)
                            self.errors.push(data.Errors[idx]);
                    }
                }
            });
        }
    }

    this.publish = function () {
        if (this.hasError()) {
            this.setError();
        } else {
            var url = appPath + 'Post/Publish/'
            var input = {
                DraftID: this.id(),
                FileID: this.fileId(),
                Type: this.type(),
                Title: this.title(),
                Meta: this.meta(),
                Contents: this.editor().getData(),
                Time: this.time(),
                Categories: this.selectedCategoriesJson(),
                OldCategories: this.oldCategoriesJson(),
                Tags: this.selectedTagsJson(),
                OldTags: this.oldTagsJson(),
                Documents: this.attachmentsJson()
            };

            $.post(url, input, function (data) {
                if (data.Result) {
                    self.successMessage(data.Message);
                    self.clearError();
                    setInterval(function () { window.location = appPath + 'Post/' + data.Data }, settings.fadeOutInterval);
                } else {
                    self.errorMessage(data.Message);
                    if (data.Errors) {
                        for (var idx = 0; idx < data.Errors.length; idx++)
                            self.errors.push(data.Errors[idx]);
                    }
                }
            });
        }
    }

    this.close = function () {
        window.location = appPath + 'Post/Manage';
    }
}

function Attachment(parent, path, fileId) {
    var self = this;
    this.parent = parent;
    this.fileId = fileId;
    this.path = ko.observable(path);
    this.id = ko.computed(function () {
        return this.path().substring(this.path().lastIndexOf('/') + 1);
    }, this);

    this.toJson = function () {
        return '{\"virtualPath": \"' + this.path() + '"}';
    }

    this.deleteAttachment = function () {
        var url = appPath + 'Post/DeleteAttachment/' + this.id() + '?fileId=' + (this.fileId ? this.fileId : '');
        $.get(url, function (data) {
            if (data.Result) {
                self.parent.remove(function (item) { return item.id() == self.id() });
            }
        });
    }
}



